import axios from "axios";
import Qs from 'qs'
import { Loading } from 'element-ui';
import { MessageBox } from 'element-ui';
import {clearTokenAndStore} from '../common/auth'
let env=process.env.NODE_ENV;
let ajaxMins={
  install:function (Vue) {
    // 拦截request,设置全局请求为ajax请求
    let ajax=axios.create({
      transformRequest: (data, headers) => {
        if (!data) {
          data = {}
        }
        return JSON.stringify(data)
      },
      baseURL:env==='production'?'http://127.0.0.1/ai-face-system/ai_face/ai-face-attendance':'http://127.0.0.1/ai-face-system/ai_face/ai-face-attendance',
      timeout:100000
    });
    ajax.interceptors.request.use((config) => {
      let token=sessionStorage.getItem("token");
      if (token == null || token == undefined || typeof (token) == 'undefined' || token === '' || token == "undefined") {
        token=""
      }
      config.headers['token'] = token;
      return config
    })

// 拦截响应response，并做一些错误处理
    ajax.interceptors.response.use((response) => {
      const data = response.data
      if (data.code!=='200'){
        // 若不是正确的返回code，且已经登录，就抛出错误
        switch (data.code) {
          case '500':
            data.message="服务器内部异常,具体原因是:"+data.message;
            break;
          case '501':
            data.message=data.message;
            break;
          case '403':
            clearTokenAndStore();
            data.message="用户信息已经过期,请重新登录";
            break;
          default:
            data.message="请求失败,请稍后重试";
            break;
        }
        return Promise.reject(data);
      }
// 根据返回的code值来做不同的处理（和后端约定）
//       data.description=data.msg;
      if (data.token){
        sessionStorage.setItem("token",data.token);
      }
      response=data.data;

      return response
    }, (err) => { // 这里是返回状态码不为200时候的错误处理
      if (err && err.response) {
        switch (err.response.status) {
          case '400':
            err.message = '请求错误'
            break

          case '401':
            err.message = '未授权，请登录'
            break

          case '403':
            err.message = '登录信息已过期，请重新登录';
            sessionStorage.clear()
            break

          case '404':
            err.message = `请求地址出错: ${err.response.config.url}`
            break

          case '408':
            err.message = '请求超时'
            break

          case '500':
            err.message = '服务器内部错误,具体原因是'+err.data.message;
            break

          case '501':
            err.message = '服务未实现'
            break

          case '502':
            err.message = '网关错误'
            break

          case '503':
            err.message = '服务不可用'
            break

          case '504':
            err.message = '网关超时'
            break

          case '505':
            err.message = 'HTTP版本不受支持'
            break

          default:
            err.message="请求失败";
            break;
        }
      }
      return Promise.reject(err)
    })
    Vue.prototype.httpAjax=ajax;
  }
}
export  {ajaxMins}
export default {
  methods: {

    /**
     *
     * @param url  请求的url
     * @param data  json 参数
     * @param config  对象采用解构方法:
     * isErrorTip  错误时弹出错误提示信息，默认为true
     * errContent  错误提示信息，不想直接显示后端的错误，则设置此值
     * disableName  控制元素禁止还没加载完再重复点击的需求，当前的唯一标识，可以把此变量名放到data里
     * isLoading   Boolean,String  是否显示加载中 默认为true true:显示加载中但没有遮罩 mask:显示加载中并且有遮罩
     * noRepeatId  唯一id 禁止重复请求，在模糊查询的时候需要，避免一直向后端请求数据，永远只获取最后一次的数据，从而大大提高性能，一般开发是不需要设置此属性
     * axiosCf axios 配置信息
     * renDisName 在渲染时禁止请求的标识，主要是在ajax错误的时候删掉，否则只要错误就无法再次请求
     * @returns {Promise}
     */
    $ajaxPost (url, data, config) {
      config = config || {}
      if (!config.axiosCf) {
        config.axiosCf = {}
      }
      config.axiosCf.data = data
      config.axiosCf.method = 'post'
      return this.$ajax(url, config)
    },
    $ajaxPut (url, data, config) {
      config = config || {}
      if (!config.axiosCf) {
        config.axiosCf = {}
      }
      config.axiosCf.data = data
      config.axiosCf.method = 'put'
      return this.$ajax(url, config)
    },
    $ajaxPatch (url, data, config) {
      config = config || {}
      if (!config.axiosCf) {
        config.axiosCf = {}
      }
      config.axiosCf.data = data
      config.axiosCf.method = 'patch'
      return this.$ajax(url, config)
    },
    $ajaxGet (url, data, config) {
      config = config || {}
      if (!config.axiosCf) {
        config.axiosCf = {}
      }
      data = data || {}
      data = Qs.stringify(data)
      if (data) {
        url = url + '?' + data
      }
      config.axiosCf.method = 'get'
      return this.$ajax(url, config)
    },
    $ajaxDelete (url, data, config) {
      config = config || {}
      if (!config.axiosCf) {
        config.axiosCf = {}
      }
      config.axiosCf.data = data
      config.axiosCf.method = 'delete'
      return this.$ajax(url, config)
    },

    $ajax (url, {isErrorTip = true, errContent, disableName, renDisName, isLoading = true, noRepeatId, axiosCf = {}} = {}) {
      return new Promise((resolve, reject) => {
        let loadingInstance;
        if (isLoading){
           loadingInstance=this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            // background: 'rgba(0, 0, 0, 0.3)'
          })
        }

        axiosCf.headers = {
          'Content-Type': 'application/json;charset=UTF-8'
        }
        axiosCf.url = url
        this.httpAjax(axiosCf).then(data => {
          if (isLoading && loadingInstance){
            loadingInstance.close()
          }
          resolve(data)
        }).catch(result => {
          debugger
          if (isLoading && loadingInstance){
            loadingInstance.close()
          }
          MessageBox({title:'错误',message:result.message,type:'error'});
          reject(result)
        })
      })
    }
  }
}
